/*
This is an Actionscript version of the Twisted Perspective Broker example
found here -:
http://twistedmatrix.com/projects/core/documentation/howto/pb-cred.html#auto18

The original python code is here
http://twistedmatrix.com/projects/core/documentation/howto/listings/pb/chatclient.py


*/


package
{
	import flash.events.Event;
	
	import org.pixelami.twisted.cred.credentials.UsernamePassword;
	import org.pixelami.twisted.internet.defer.Deferred;
	import org.pixelami.twisted.spread.flavors.Referencable;
	import org.pixelami.twisted.spread.pb.Broker;
	import org.pixelami.twisted.spread.pb.PBClientFactory;
	import org.pixelami.twisted.spread.pb.RemoteReference;

	public class PBChatClientObject extends Referencable
	{
		private var factory:PBClientFactory;
		private var group:*
		public var dialog:*;
		
		public function PBChatClientObject()
		{
			super();
			factory = new PBClientFactory();
		}
		
		public function onClientConnect(evt:Event):void
		{
			trace("onClientConnect - "+evt);
			var broker:Broker = Broker(evt.target);
			factory.clientConnectionMade(broker);
			
			var def1:Deferred = factory.login(new UsernamePassword("alice", "1234"),
                             this);
                     
        	def1.addCallback(this.connected);                            
		}
		
		public function connected(perspective:RemoteReference):void
	    {
	        //trace( "connected, joining group #lookingForFourth" );
	        var d:Deferred = perspective.callRemote("joinGroup", "#lookingForFourth");
	        d.addCallback(this.gotGroup);
	    }
	
	    public function gotGroup(g:RemoteReference):void
	    {
	        //trace( "joined group, now sending a message to all members" );
	        this.group = g;
	    }
	    
	    public function shutdown(...args):void
	    {
	    	trace("shutdown args = "+args);
	    }

	    public function remote_print(message:String):void
	    {
	    	dialog.addMessage(message);
	    }
	    
	    public function sendLine(str:String):void
	    {
	    	var d:Deferred = this.group.callRemote("send", str);
	    	d.addCallback(handleSuccess);
	    }
	    
	    public function handleSuccess(...args):void
	    {
	    	//trace("handleSuccess = "+args);
	    }

	}
}